<?php

namespace App\Models\Common;

use App\Models\BaseModel;
use App\Models\Cruise\CruiseCheckAlbumModel;
use App\Models\Traits\KfSoftDeletes;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class ResourcesModel extends BaseModel
{
    use HasFactory, KfSoftDeletes;

    protected $table = "resources";

    protected $fillable = [
        'businessId',
        'module',
        'business',
        'name',
        'url',
        'isPublic',
        'sort',
        'extra',
        'isDeleted',
        'createdAt',
        'createdByUid',
        'updatedAt',
        'updatedByUid',
    ];

    public static array $privateResourcesFields = [
        "collectionPersonIdentityCardFront",
        "collectionPersonIdentityCardBack",
        "legalPersonIdentityCardFront",
        "legalPersonIdentityCardBack",
        //"businessLicenseImg"   营业执照变成公有的
        "collectionPersonIdentityCardWithBack", //收款人手持身份证国徽面
        "collectionPersonIdentityCardWithFront",//收款人手持身份证人像面
        "legalPersonIdentityCardWithFront",     //法人手持身份证人像面
        "legalPersonIdentityCardWithBack",      //法人手持身份证国徽面
        'payeeIdentityCardFront',               //收款人身份证人像面
        'payeeIdentityCardBack',                //收款人身份证国徽面
    ];

    const EXTRA_TYPE_IMAGE = 'image';
    const EXTRA_TYPE_VIDEO = 'video';

    const EXTRA_TYPES = [
        self::EXTRA_TYPE_IMAGE,
        self::EXTRA_TYPE_VIDEO,
    ];

    const IS_PUBLIC_YES = 1;
    const IS_PUBLIC_NO  = 0;

    const MODULE_TYPE_WORK_ORDER = "WORK_ORDER";
    const MODULE_TYPE_CRUISE = 'CRUISE';
    const MODULE_TYPE_SITE = 'SITE';
    const MODULE_TYPE_CHECK = 'CHECK'; // 稽核
    const MODULE_TYPE_COLLEGE = 'COLLEGE';
    const MODULE_TYPE_SITE_MALL = 'SITE_MALL';
    const MODULE_TYPE_CHECK_USER_QRCODE = 'CHECK_QRCODE';  //稽核二维码
    const MODULE_TYPE_SHOP = 'SHOP';
    const MODULE_TYPE_APPRAISE = 'appraise';//评价反馈
    const MODULE_TYPE_WG_AUDIT = 'WG_AUDIT';//网规评价
    const MODULE_TYPE_OPEN_SHOP = 'OPEN_SHOP';//开店
    const MODULE_TYPE_CASHBOOK_ADD = 'CASHBOOK_ADD';//记账本-记一笔
    const MODULE_TYPE_MOVING_LING_MARKING_DESC = 'MOVING_LING_MARKING_DESC'; //动线标注
    const MODULE_TYPE_TOUR = 'TOUR'; // 云巡店
    const MODULE_TYPE_COMMUNICATE_RECORD = 'MODULE_TYPE_COMMUNICATE_RECORD'; // 大客户部沟通记录
    const MODULE_TYPE_BUSINESS_CIRCLE_RECORD = 'BUSINESS_CIRCLE_RECORD'; // 商圈记录
    const MODULE_TYPE_INTENDED_SITE_LOCATION = 'INTENDED_SITE_LOCATION'; // 意向址记录
    const MODULE_TYPE_WORK_ORDER_PRODUCT_SELECTION_PROPOSAL = 'WORK_ORDER_PRODUCT_SELECTION_PROPOSAL'; // 选品建议表
    const MODULE_TYPE_CRUISE_ACTIVITY = 'CRUISE_ACTIVITY'; // 门店活动



    const BUSINESS_WORK_ORDER_FUNCTION_OPEN = "FUNCTION_OPEN";
    const BUSINESS_WORK_ORDER_PROBLEM_FEEDBACK = 'PROBLEM_FEEDBACK';
    const BUSINESS_CRUISE_PROJECT_TIPS = 'CRUISE_PROJECT_TIPS';
    const BUSINESS_CRUISE_ORDERS = 'BUSINESS_CRUISE_ORDERS';
    const BUSINESS_SITE_ORDERS = 'BUSINESS_SITE_ORDERS';
    const BUSINESS_CHECK_ORDERS = 'BUSINESS_CHECK_ORDERS';
    const BUSINESS_COLLEGE_COURSES = 'BUSINESS_COLLEGE_COURSES';
    const BUSINESS_SITE_LOCATION_MALL = 'BUSINESS_SITE_LOCATION_MALL';
    const BUSINESS_CHECK_USER_QRCODE = 'BUSINESS_CHECK_USER_QRCODE';
    const BUSINESS_CHECK_ERROR_REPORT_VIDEO = 'BUSINESS_CHECK_ERROR_REPORT_VIDEO'; // 稽核 - 报备单，异常报备视频
    const BUSINESS_CHECK_RECTIFY_FILES = 'BUSINESS_CHECK_RECTIFY_FILES'; // 稽核 - 整改单整改图片、视频
    const BUSINESS_SHOP_ARCHIVE = 'BUSINESS_SHOP_ARCHIVE';//店铺档案- 营业执照和食品经营许可证
    const BUSINESS_CHECK_ALBUM = 'BUSINESS_CHECK_ALBUM'; //稽核相册
    const BUSINESS_APPRAISE = 'BUSINESS_APPRAISE';//评价反馈
    const BUSINESS_OPEN_SHOP_PREPARATION = 'BUSINESS_PREPARATION'; // 开店-筹备阶段

    const BUSINESS_WG_AUDIT = 'BUSINESS_WG_AUDIT';//网规评价
    const BUSINESS_WG_HEAT_MAP = 'BUSINESS_WG_HEAT_MAP';//网规热力图
    //可开区域文件tag
    const BUSINESS_OPEN_DISTRICT = 'BUSINESS_OPEN_DISTRICT';
    const BUSINESS_OPEN_SHOP_SITE_LOCATION = 'BUSINESS_SITE_LOCATION'; // 开店-选址阶段
    const BUSINESS_CASHBOOK_ADD = 'BUSINESS_CASHBOOK_ADD'; // 记账本-记一笔
    const BUSINESS_MOVING_LING_MARKING_DESC = 'BUSINESS_MOVING_LING_MARKING_DESC'; //动线标注
    const BUSINESS_OPEN_TOUR = 'BUSINESS_TOUR'; // 云巡店-素材库
    const BUSINESS_OPEN_TOUR_INPUT = 'BUSINESS_TOUR_INPUT'; // 云巡店-表单
    const BUSINESS_COMMUNICATE_RECORD = 'BUSINESS_COMMUNICATE_RECORD'; // 大客户部沟通记录
    const BUSINESS_BUSINESS_CIRCLE_RECORD = 'BUSINESS_CIRCLE_RECORD'; // 商圈记录
    const BUSINESS_INTENDED_SITE_LOCATION = 'INTENDED_SITE_LOCATION'; // 意向址记录
    const BUSINESS_TYPE_WORK_ORDER_PRODUCT_SELECTION_PROPOSAL = 'BUSINESS_WORK_ORDER_PRODUCT_SELECTION_PROPOSAL'; // 选品建议表
    const BUSINESS_CRUISE_ACTIVITY_INPUT = 'BUSINESS_CRUISE_ACTIVITY'; // 门店活动-表单

    public function getExtraArrAttribute(): array
    {
        return json_decode($this->extra, true) ?? [];
    }

    /**
     * 获取模块对应业务ID涉及资源信息
     *
     * @param string $module
     * @param string $business
     * @param int $businessId
     * @param array $fieldsName
     * @return object
     */
    public static function getModuleBusinessResources(
        string $module,
        string $business,
        int $businessId,
        array $fieldsName = []
    ): object {
        $resources = self::query()->where("module", $module)
                         ->when($business, function ($query) use ($business) {
                             $query->where("business", $business);
                         })
                         ->where("businessId", $businessId)
                         ->where("isDeleted", 0)
                         ->get();
        $fieldsName = $fieldsName ? $fieldsName : $resources->pluck('name')->unique()->values()->toArray();

        return (object)collect($fieldsName)->map(function ($v) use ($resources) {
            return [
                "key" => $v,
                "url" => $resources->where("name", $v)->map(function ($v) {
                    if ($v->isPublic == 1) {
                        $v->url = picturePath($v->url);
                    } else {
                        $v->url = privateFilePath($v->url);
                    }
                    return $v;
                })->pluck("url")->values()->toArray()
            ];
        })->values()->pluck("url", "key")->toArray();
    }

    /**
     * 临时资源存储
     *
     * @var array
     */
    public static array $resourcesTempSaveMap = [];

    /**
     * 构建临时资源存储
     *
     * @param string $module
     * @param string $business
     * @param string $name
     * @param int $businessId
     * @param string $url
     * @param int $isPublic
     * @param string $extra
     * @param int $createdByUid
     */
    public static function moduleBusinessResourcesBuild(
        string $module,
        string $business,
        string $name,
        int $businessId,
        string $url,
        int $isPublic = self::IS_PUBLIC_YES,
        string $extra = "",
        int $createdByUid = 0
    ) {

        array_push(
            self::$resourcesTempSaveMap, [
            "module"       => $module,
            "business"     => $business,
            "name"         => $name,
            "businessId"   => $businessId,
            "url"          => $url,
            "isPublic"     => $isPublic,
            "extra"        => $extra,
            "createdAt"    => time(),
            "updatedAt"    => time(),
            "createdByUid" => $createdByUid,
        ]
        );
    }

    /**
     * 保存临时资源
     */
    public static function moduleBusinessResourcesSave()
    {
        if (!empty(self::$resourcesTempSaveMap)) {
            self::query()->insert(self::$resourcesTempSaveMap);
        }
        self::$resourcesTempSaveMap = [];
    }


    /**
     * 单条资源更新 / 添加
     *
     * @param string $module
     * @param string $business
     * @param string $name
     * @param int $businessId
     * @param array $url
     * @param int $isPublic
     * @param string $extra
     * @throws Exception
     */
    public static function moduleBusinessSingleResourcesUpdate(
        string $module,
        string $business,
        string $name,
        int $businessId,
        array $url,
        int $isPublic = self::IS_PUBLIC_YES,
        string $extra = ""
    ) {
        $resourceModel = self::query()->where("module", $module)
            ->where("business", $business)
            ->where("name", $name)
            ->where("businessId", $businessId);

        $resourceModel->update(["isDeleted" => 1]);

        $baseData = [
            "module"     => $module,
            "business"   => $business,
            "name"       => $name,
            "businessId" => $businessId,
            "isPublic"   => $isPublic,
            "extra"      => $extra,
            "createdAt"  => time(),
            "updatedAt"  => time()
        ];

        self::query()->insert(collect($url)->map(function ($url) use ($baseData) {
            $url = ltrim(parse_url($url, PHP_URL_PATH), '/');
            return array_merge($baseData, ["url" => $url]);
        })->values()->toArray());
    }

    /**
     * 仅更新指定资源字段数据
     *
     * @param array $resources
     * @param string $module
     * @param string $business
     * @param int $businessId
     * @param string $extra
     */
    public static function moduleBusinessResourcesCustomFieldsUpdate(
        array $resources,
        string $module,
        string $business,
        int $businessId,
        string $extra = ""
    ) {
        if (!empty($resources)) {
            self::query()->where("module", $module)
                ->where("business", $business)
                ->where("businessId", $businessId)
                ->whereIn("name", array_keys($resources))
                ->update(["isDeleted" => 1]);

            $baseData = [
                "module"     => $module,
                "business"   => $business,
                "businessId" => $businessId,
                "extra"      => $extra,
                "createdAt"  => time(),
                "updatedAt"  => time()
            ];

            $insertData = [];
            collect($resources)->each(function ($resource, $key) use (&$insertData, $baseData) {
                collect($resource)->map(function ($url) use (&$insertData, $baseData, $key) {
                    $url = ltrim(parse_url($url, PHP_URL_PATH), '/');

                    return array_push(
                        $insertData,
                        array_merge(
                            $baseData,
                            [
                                "url"      => $url,
                                "name"     => $key,
                                "isPublic" => in_array(
                                    $key,
                                    self::$privateResourcesFields
                                ) ? self::IS_PUBLIC_NO : self::IS_PUBLIC_YES
                            ]
                        )
                    );
                });
            });

            self::query()->insert($insertData);
        }
    }

    /**
     * 模块单条业务资源整体更新
     *
     * @param array $resources
     * @param string $module
     * @param string $business
     * @param int $businessId
     * @param string $extra
     */
    public static function moduleBusinessResourcesUpdate(
        array $resources,
        string $module,
        string $business,
        int $businessId,
        string $extra = ""
    ) {
        self::query()->where("module", $module)
            ->where("business", $business)
            ->where("businessId", $businessId)
            ->update(["isDeleted" => 1]);

        $baseData = [
            "module"     => $module,
            "business"   => $business,
            "businessId" => $businessId,
            "extra"      => $extra,
            "createdAt"  => time(),
            "updatedAt"  => time()
        ];

        $insertData = [];
        collect($resources)->each(function ($resource, $key) use (&$insertData, $baseData) {
            collect($resource)->map(function ($url) use (&$insertData, $baseData, $key) {
                $url = ltrim(parse_url($url, PHP_URL_PATH), '/');

                return array_push(
                    $insertData,
                    array_merge(
                        $baseData,
                        [
                            "url"      => $url,
                            "name"     => $key,
                            "isPublic" => in_array(
                                $key,
                                self::$privateResourcesFields
                            ) ? self::IS_PUBLIC_NO : self::IS_PUBLIC_YES
                        ]
                    )
                );
            });
        });

        self::query()->insert($insertData);
    }


    /**
     * 模块单条业务资源整体更新-多个不同资源附加信息
     *
     * @param array $resources
     * @param string $module
     * @param string $business
     * @param int $businessId
     * @param array $names
     */
    public static function moduleBusinessResourcesBatchUpdate(
        array $resources,
        string $module,
        string $business,
        int $businessId,
        array $names
    ) {
        self::query()->where("module", $module)
            ->where("business", $business)
            ->where("businessId", $businessId)
            ->whereIn('name', $names)
            ->update(["isDeleted" => 1]);

        $baseData = [
            "module" => $module,
            "business" => $business,
            "businessId" => $businessId,
            "extra" => "",
            "createdAt" => time(),
            "updatedAt" => time()
        ];

        $insertData = [];
        collect($resources)->each(function ($resource) use (&$insertData, $baseData) {
            $url = $resource['url'];
            $url = ltrim(parse_url($url, PHP_URL_PATH), '/');

            $sort = $resource['sort'];
            $name = $resource['resourcesName'];
            unset($resource['url'], $resource['sort'], $resource['resourcesName']);
            $extra = "";
            if ($resource) {
                $extra = json_encode($resource);
            }
            return array_push(
                $insertData,
                array_merge(
                    $baseData,
                    [
                        "url" => $url,
                        "name" => $name,
                        "isPublic" => self::IS_PUBLIC_YES,
                        "extra" => $extra,
                        "sort" => $sort,
                    ]
                )
            );
        });
        self::query()->insert($insertData);
    }


    /**
     * 获取模块对应业务ID涉及资源信息-多个不同资源附加信息
     *
     * @param string $module
     * @param string $business
     * @param int $businessId
     * @return array
     */
    public static function getModuleBusinessBatchResources(
        string $module,
        string $business,
        int $businessId
    ): array
    {
        return self::query()->where("module", $module)
            ->when($business, function ($query) use ($business) {
                $query->where("business", $business);
            })
            ->where("businessId", $businessId)
            ->select(['name', 'url', 'sort', 'extra'])
            ->orderBy('sort')
            ->get()
            ->toArray();
    }

}
